<?php
class Dispatcher{
	var $request;
	var $erreur_404 = 1;
	var $erreur_505 = 2;
		
	public function __construct($url=null){
		//si l'url à été informer
		if($url){
			$this->request = $url;
		} else {
			$this->request = new Request();
		}
		Router::parse($this->request->url,$this->request);
		if(/*$this->request->controller==='' && (!isset($_SESSION['email'])) || 
		$this->request->controller==='accueil.php'*/false){
			require ROOT.DS.'view'.DS.'accueil.php';
			die();
		} else {
			
			$controller = $this->loadController();
			
			if(!in_array($this->request->action,array_diff(get_class_methods($controller),
			get_class_methods('Controller')))){
				$this->error($this->erreur_404);
			} 
			//on affiche pas les messages d'erreurs retouner par la fonction en l'appelant avec @ ----important----!
			@ call_user_func_array(array($controller,$this->request->action),$this->request->params);
			if(!is_a($controller,'AjaxController') && !is_a($controller,'FichierAppelOffreController')){
				$controller->render($this->request->action);	
			} else if(is_a($controller,'FichierAppelOffreController')){
				$controller->renderPDF($this->request->action);
			}
		
		}
		
	}
	
	public function loadController(){
		$name = ucfirst($this->request->controller).'Controller';
		$file = ROOT.DS.'controller'.DS.$name.'.php';
		if(is_file($file)){
			require_once $file;
			return new $name($this->request);
		} else {
			echo ROOT.DS;
			echo $file;
			$this->error($this->erreur_404);
			return false;
		}
		
	}
	
	public function error($code){
		
		if($code==$this->erreur_404){
			$controller = new Controller($this->request);
			$controller->render('/404.php');	
		} else if($code==$this->erreur_505){
			
		}
		
		die();
	}
}